package com.txf.net_okhttp3library;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;

/**
 * @author txf
 * @create 2019/1/31 0031
 * @请求队列
 */
public class HttpQueue {
    private static HttpQueue mHttpQueue;

    public synchronized static HttpQueue newHttpQueue() {
        if (mHttpQueue == null) {
            mHttpQueue = new HttpQueue();
        }
        return mHttpQueue;
    }

    /**
     * 取消指定标识的网络请求
     *
     * @param tag 网络请求标识
     */
    public void cancelRequest(int tag) {
        for (Call call : HttpClient.getInstance().getOkHttpClient().dispatcher().queuedCalls()) {
            if (call.request().tag().equals(tag))
                call.cancel();
        }
    }

    /**
     * 取消全部网络请求
     */
    public void cancelRequestAll() {
        for (Call call : HttpClient.getInstance().getOkHttpClient().dispatcher().queuedCalls()) {
            call.cancel();
        }
    }

    /**
     * 添加请求到队列(发送请求)
     *
     * @param tag 网络请求标识
     */
    public void addRequest(int tag, okhttp3.Request request, final Callback l) {
        Request.Builder builder = request.newBuilder();
        builder.tag(tag);
        Call call = HttpClient.getInstance().getOkHttpClient().newCall(builder.build());
        call.enqueue(l);
    }
}
